<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        .container {
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div class="container">abcdefgABCD</div>
    <script>
        //打字游戏
        // 1.把所有的字符串包裹一个span
        var containerEle = document.querySelector(".container");
        // trim()去掉首位空格；
        var str = containerEle.innerHTML.trim();
        var newStr = "";
        for (var i = 0; i < str.length; i++) {
            // console.log(str[i]);
            newStr += `<span>${str[i]}</span>`;
        }
        // console.log(newStr);
        containerEle.innerHTML = newStr;
        var spans = document.querySelectorAll(".container span");
        // 2.按对应的按键的时候改变 字符的颜色
        document.onkeydown = function(e) {
            var e = e || window.event;
            var key = e.key;
            spans.forEach(function(item) {
                if (key == item.innerHTML) {
                    item.style.color = "red";
                }
            });
        };
    </script>
</body>

</html>